package com.alfayun.fiscalriskanalysis.importer;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.alfayun.fiscalriskanalysis.report.CellService;
import com.alfayun.fiscalriskanalysis.report.NoSuchReportException;
import com.alfayun.fiscalriskanalysis.report.Report;

public class FS001Importer implements Importer {
	
	private int[] columnNumbers = {2, 3, 6, 7};
	
	public ImportResult importReport(InputStream input, Report report, CellService cellService) throws IOException, NoSuchReportException {
		var cells = new ArrayList<com.alfayun.fiscalriskanalysis.report.Cell>();

		try (Workbook workbook = WorkbookFactory.create(input)) {
			var sheet = workbook.getSheetAt(0);
			var errorDetails = new ArrayList<ImportErrorDetailItem>();

			for (int i = 5; i <= sheet.getLastRowNum(); ++i) {
				Row row = sheet.getRow(i);
				for (int j = 0; j < columnNumbers.length; j++) {
					
					try {
						com.alfayun.fiscalriskanalysis.report.Cell cell = new com.alfayun.fiscalriskanalysis.report.Cell();
						cell.report = report;
						cell.rowIndex = String.valueOf(i + 1 - 5);
						cell.columnIndex = String.valueOf(columnNumbers[j]);
						cell.value = getCellAsString(row.getCell(columnNumbers[j]));
						cells.add(cell);
					} catch (Exception e) {
						errorDetails.add(new ImportErrorDetailItem(e.getMessage(), i, columnNumbers[j], getCellAsString(row.getCell(columnNumbers[j]))));
					}
				}
			}
			
			cellService.add(report.getId(), cells);

			if (CollectionUtils.isNotEmpty(errorDetails)) {

				throw new ImportFailedException(new ImportResult("failed", errorDetails));
			}

			return new ImportResult("successful", null);
		}
	}

	private String getCellAsString(Cell cell) {
		switch (cell.getCellType()) {
		case STRING:
			return cell.getStringCellValue();

		case NUMERIC:
			return Integer.toString((int) cell.getNumericCellValue());

		default:
			return "";
		}
	}


}
